<template>
  <div class="feedback-container">
    <!-- 顶部操作栏 -->
    <div class="header-actions">
      <el-button type="primary" @click="handleCreateClick">提交反馈</el-button>
      <el-button @click="fetchList">刷新</el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="searchForm" inline class="search-form">
      <el-form-item label="关键词">
        <el-input v-model="searchForm.keyword" placeholder="搜索标题或内容" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="处理状态" clearable>
          <el-option label="待处理" value="pending" />
          <el-option label="处理中" value="processing" />
          <el-option label="已解决" value="resolved" />
          <el-option label="已关闭" value="closed" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="searchForm.feedbackType" placeholder="反馈类型" clearable>
          <el-option label="错误报告" value="bug" />
          <el-option label="功能建议" value="feature" />
          <el-option label="投诉" value="complaint" />
          <el-option label="建议" value="suggestion" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级">
        <el-select v-model="searchForm.priority" placeholder="优先级" clearable>
          <el-option label="低" value="low" />
          <el-option label="中" value="medium" />
          <el-option label="高" value="high" />
          <el-option label="紧急" value="urgent" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 反馈列表 -->
    <el-table 
      :data="tableData.list" 
      :height="view.height - 380" 
      border 
      style="width: 100%"
      v-loading="tableData.loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
      <el-table-column prop="feedbackType" label="类型" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.feedbackType === 'bug'" type="danger">错误</el-tag>
          <el-tag v-else-if="scope.row.feedbackType === 'feature'" type="success">功能</el-tag>
          <el-tag v-else-if="scope.row.feedbackType === 'complaint'" type="warning">投诉</el-tag>
          <el-tag v-else-if="scope.row.feedbackType === 'suggestion'" type="info">建议</el-tag>
          <el-tag v-else>其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="100">
        <template #default="scope">
          <el-tag 
            :type="scope.row.priority === 'urgent' ? 'danger' : 
                  scope.row.priority === 'high' ? 'warning' : 
                  scope.row.priority === 'medium' ? '' : 'info'"
          >
            {{ 
              scope.row.priority === 'urgent' ? '紧急' : 
              scope.row.priority === 'high' ? '高' : 
              scope.row.priority === 'medium' ? '中' : '低' 
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag 
            :type="scope.row.status === 'pending' ? 'info' : 
                  scope.row.status === 'processing' ? 'warning' : 
                  scope.row.status === 'resolved' ? 'success' : 
                  scope.row.status === 'closed' ? '' : 'danger'"
          >
            {{ 
              scope.row.status === 'pending' ? '待处理' : 
              scope.row.status === 'processing' ? '处理中' : 
              scope.row.status === 'resolved' ? '已解决' : 
              scope.row.status === 'closed' ? '已关闭' : '已拒绝' 
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isRead" label="已读" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.isRead ? 'success' : 'info'">
            {{ scope.row.isRead ? '已读' : '未读' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="170" />
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleViewClick(scope.row)">查看</el-button>
          <el-button size="small" type="primary" @click="handleUpdateClick(scope.row)">处理</el-button>
          <el-button size="small" type="danger" @click="handleDeleteClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="searchForm.page"
        v-model:page-size="searchForm.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 创建/编辑表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.type === 'create' ? '提交反馈' : dialog.type === 'update' ? '处理反馈' : '反馈详情'"
      width="650px"
    >
      <el-form
        ref="formRef"
        :model="form"
        label-width="100px"
        :disabled="dialog.type === 'view'"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" :disabled="dialog.type === 'update'" />
        </el-form-item>
        
        <el-form-item label="类型" prop="feedbackType">
          <el-select v-model="form.feedbackType" placeholder="请选择反馈类型" :disabled="dialog.type === 'update'">
            <el-option label="错误报告" value="bug" />
            <el-option label="功能建议" value="feature" />
            <el-option label="投诉" value="complaint" />
            <el-option label="建议" value="suggestion" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            rows="5"
            placeholder="请描述详细信息"
            :disabled="dialog.type === 'update'"
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email" v-if="dialog.type === 'create'">
          <el-input v-model="form.email" placeholder="请输入联系邮箱" />
        </el-form-item>
        
        <template v-if="dialog.type === 'update'">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择处理状态">
              <el-option label="待处理" value="pending" />
              <el-option label="处理中" value="processing" />
              <el-option label="已解决" value="resolved" />
              <el-option label="已关闭" value="closed" />
              <el-option label="已拒绝" value="rejected" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="请选择优先级">
              <el-option label="低" value="low" />
              <el-option label="中" value="medium" />
              <el-option label="高" value="high" />
              <el-option label="紧急" value="urgent" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="处理备注" prop="handlerRemark">
            <el-input
              v-model="form.handlerRemark"
              type="textarea"
              rows="3"
              placeholder="请输入处理备注"
            />
          </el-form-item>
        </template>
        
        <template v-if="dialog.type === 'view'">
          <el-form-item label="状态">
            <el-tag 
              :type="form.status === 'pending' ? 'info' : 
                    form.status === 'processing' ? 'warning' : 
                    form.status === 'resolved' ? 'success' : 
                    form.status === 'closed' ? '' : 'danger'"
            >
              {{ 
                form.status === 'pending' ? '待处理' : 
                form.status === 'processing' ? '处理中' : 
                form.status === 'resolved' ? '已解决' : 
                form.status === 'closed' ? '已关闭' : '已拒绝' 
              }}
            </el-tag>
          </el-form-item>
          
          <el-form-item label="处理备注" v-if="form.handlerRemark">
            <div>{{ form.handlerRemark }}</div>
          </el-form-item>
          
          <el-form-item label="处理时间" v-if="form.handledAt">
            <div>{{ form.handledAt }}</div>
          </el-form-item>
          
          <!-- 评分区域 -->
          <template v-if="['resolved', 'closed'].includes(form.status) && !form.rating">
            <el-divider />
            <el-form-item label="评分">
              <el-rate v-model="ratingForm.rating" :max="5" />
            </el-form-item>
            <el-form-item label="评价">
              <el-input
                v-model="ratingForm.userComment"
                type="textarea"
                rows="2"
                placeholder="请输入您的评价"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitRating">提交评价</el-button>
            </el-form-item>
          </template>
          
          <!-- 已评分显示区域 -->
          <template v-if="form.rating">
            <el-divider />
            <el-form-item label="我的评分">
              <el-rate v-model="form.rating" disabled />
            </el-form-item>
            <el-form-item label="我的评价" v-if="form.userComment">
              <div>{{ form.userComment }}</div>
            </el-form-item>
          </template>
        </template>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" v-if="dialog.type !== 'view'">
            {{ dialog.type === 'create' ? '提交' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";

// 视图高度响应式调整
const view = reactive({
  height: window.innerHeight,
});

// 监听窗口大小变化
window.onresize = () => {
  view.height = window.innerHeight;
};

// 查询表单
const searchForm = reactive({
  page: 1,
  size: 20,
  keyword: "",
  status: "",
  feedbackType: "",
  priority: "",
  sortField: "createdAt",
  sortOrder: "DESC",
});

// 表格数据
const tableData = reactive({
  list: [],
  total: 0,
  loading: false,
});

// 表单引用
const formRef = ref(null);

// 表单对象
const form = reactive({
  id: null,
  userId: null,
  userName: "",
  email: "",
  feedbackType: "suggestion",
  title: "",
  content: "",
  priority: "medium",
  status: "pending",
  handlerId: null,
  handlerName: "",
  handlerRemark: "",
  handledAt: null,
  isRead: false,
  createdAt: null,
  updatedAt: null,
});

// 评分表单
const ratingForm = reactive({
  rating: 5,
  userComment: "",
});

// 对话框控制
const dialog = reactive({
  visible: false,
  type: "create", // create, update, view
});

// 获取反馈列表
const fetchList = async () => {
  tableData.loading = true;
  try {
    const response = await axios.get("/algorithmApi/api/feedback", { params: searchForm });
    tableData.list = response.data.list.map(item => ({
      ...item,
      createdAt: dayjs(item.createdAt).format("YYYY-MM-DD HH:mm:ss"),
      updatedAt: item.updatedAt ? dayjs(item.updatedAt).format("YYYY-MM-DD HH:mm:ss") : null,
      handledAt: item.handledAt ? dayjs(item.handledAt).format("YYYY-MM-DD HH:mm:ss") : null,
    }));
    tableData.total = response.data.total;
  } catch (error) {
    console.error("获取反馈列表失败", error);
    ElMessage.error("获取反馈列表失败");
  } finally {
    tableData.loading = false;
  }
};

// 获取反馈详情
const fetchDetail = async (id) => {
  try {
    const response = await axios.get(`/algorithmApi/api/feedback/${id}`);
    Object.assign(form, {
      ...response.data,
      createdAt: response.data.createdAt ? dayjs(response.data.createdAt).format("YYYY-MM-DD HH:mm:ss") : null,
      updatedAt: response.data.updatedAt ? dayjs(response.data.updatedAt).format("YYYY-MM-DD HH:mm:ss") : null,
      handledAt: response.data.handledAt ? dayjs(response.data.handledAt).format("YYYY-MM-DD HH:mm:ss") : null,
    });
    
    // 如果未读，则标记为已读
    if (!response.data.isRead) {
      markAsRead(id);
    }
  } catch (error) {
    console.error("获取反馈详情失败", error);
    ElMessage.error("获取反馈详情失败");
  }
};

// 标记为已读
const markAsRead = async (id) => {
  try {
    await axios.put(`/algorithmApi/api/feedback/${id}/read`);
  } catch (error) {
    console.error("标记已读失败", error);
  }
};

// 提交反馈
const createFeedback = async () => {
  try {
    await axios.post("/algorithmApi/api/feedback", form);
    ElMessage.success("提交反馈成功");
    dialog.visible = false;
    resetForm();
    fetchList();
  } catch (error) {
    console.error("提交反馈失败", error);
    ElMessage.error("提交反馈失败");
  }
};

// 更新反馈
const updateFeedback = async () => {
  try {
    await axios.put(`/algorithmApi/api/feedback/${form.id}`, {
      status: form.status,
      priority: form.priority,
      handlerRemark: form.handlerRemark,
      isRead: true,
    });
    ElMessage.success("更新反馈成功");
    dialog.visible = false;
    fetchList();
  } catch (error) {
    console.error("更新反馈失败", error);
    ElMessage.error("更新反馈失败");
  }
};

// 删除反馈
const deleteFeedback = async (id) => {
  try {
    await axios.delete(`/algorithmApi/api/feedback/${id}`);
    ElMessage.success("删除反馈成功");
    fetchList();
  } catch (error) {
    console.error("删除反馈失败", error);
    ElMessage.error("删除反馈失败");
  }
};

// 提交评分
const submitRating = async () => {
  try {
    await axios.post(`/algorithmApi/api/feedback/${form.id}/rating`, ratingForm);
    ElMessage.success("提交评价成功");
    fetchDetail(form.id);
  } catch (error) {
    console.error("提交评价失败", error);
    ElMessage.error("提交评价失败");
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    userId: null,
    userName: "",
    email: "",
    feedbackType: "suggestion",
    title: "",
    content: "",
    priority: "medium",
    status: "pending",
    handlerId: null,
    handlerName: "",
    handlerRemark: "",
    handledAt: null,
    isRead: false,
    createdAt: null,
    updatedAt: null,
  });
};

// 处理搜索
const handleSearch = () => {
  searchForm.page = 1;
  fetchList();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    page: 1,
    size: 20,
    keyword: "",
    status: "",
    feedbackType: "",
    priority: "",
    sortField: "createdAt",
    sortOrder: "DESC",
  });
  fetchList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  searchForm.page = val;
  fetchList();
};

// 处理页大小变化
const handleSizeChange = (val) => {
  searchForm.size = val;
  searchForm.page = 1;
  fetchList();
};

// 处理创建点击
const handleCreateClick = () => {
  resetForm();
  dialog.type = "create";
  dialog.visible = true;
};

// 处理更新点击
const handleUpdateClick = (row) => {
  fetchDetail(row.id);
  dialog.type = "update";
  dialog.visible = true;
};

// 处理查看点击
const handleViewClick = (row) => {
  fetchDetail(row.id);
  dialog.type = "view";
  dialog.visible = true;
};

// 处理删除点击
const handleDeleteClick = (row) => {
  ElMessageBox.confirm("确定要删除这条反馈吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteFeedback(row.id);
    })
    .catch(() => {});
};

// 处理表单提交
const handleSubmit = () => {
  if (dialog.type === "create") {
    createFeedback();
  } else {
    updateFeedback();
  }
};

// 加载初始数据
onMounted(() => {
  fetchList();
});
</script>

<style lang="scss" scoped>
.feedback-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .header-actions {
    margin-bottom: 15px;
  }
  
  .search-form {
    margin-bottom: 15px;
    padding: 15px;
    border-radius: 4px;
  }
  
  .pagination-container {
    margin-top: 15px;
    text-align: right;
  }
}
</style>
